package diskwatch

import (
	"context"

	"github.com/spf13/viper"
	"go.uber.org/zap"
)

func NewMonitor(logger *zap.Logger, conf *viper.Viper) *Monitor {
	m := &Monitor{
		pms:    make(map[string]*PartitionMonitor),
		logger: logger,
	}

	pm := NewPartitionMonitor(logger, conf)
	monitors, _ := conf.Get("watch.disk.monitor").([]any)
	pathMonitors := make([]*PathMonitor, 0)
	for _, monitor := range monitors {
		mConf := viper.New()
		mConf.Set("monitor", monitor)
		pathMonitors = append(pathMonitors, NewPathMonitors(logger, mConf)...)
	}

	for _, p := range pathMonitors {
		_, ok := m.pms[p.monutPoint]
		if !ok {
			newPM := *pm
			m.pms[p.monutPoint] = &newPM
			m.pms[p.monutPoint].monutPoint = p.monutPoint
		}
		m.pms[p.monutPoint].paths = append(m.pms[p.monutPoint].paths, p)
		if m.pms[p.monutPoint].used < p.used {
			m.pms[p.monutPoint].used = p.used
		}
	}

	for k, pm := range m.pms {
		if pm.used == 0 {
			pm.used = pm.generalUsed
		}
		m.pms[k] = pm
	}

	return m
}

type Monitor struct {
	pms    map[string]*PartitionMonitor
	logger *zap.Logger
}

func (m *Monitor) Handle(ctx context.Context) {
	m.logger.Info("[磁盘守护]监控功能启动...")
	for key, pm := range m.pms {
		m.logger.Info("[磁盘守护]磁盘分区监控", zap.String("partition", key))
		go pm.Handle(ctx)
	}
}
